package org.ciallo.simplemusicplayer.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.adapter.SongAdapter;
import org.ciallo.simplemusicplayer.data.model.Song;
import org.ciallo.simplemusicplayer.dialog.SongOptionsDialogFragment;
import org.ciallo.simplemusicplayer.viewmodel.LocalMusicViewModel;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jukomu
 * @Description: 显示特定歌手的所有歌曲的 Activity
 * @Package: org.ciallo.simplemusicplayer.activity
 * @Project: SimpleMusicPlayer
 * @name: ArtistSongsActivity
 * @Date: 2025/6/2-22:08
 * @Filename: ArtistSongsActivity
 */
public class ArtistSongsActivity extends AppCompatActivity {

    public static final String EXTRA_ARTIST_ID = "extra_artist_id";
    public static final String EXTRA_ARTIST_NAME = "extra_artist_name";
    public static final String EXTRA_ARTIST_ALBUM_ART_URI = "extra_artist_album_art_uri"; // 用于顶部显示

    private long artistId;
    private String artistName;
    private String artistCoverUri;

    private Toolbar toolbar;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private ImageView ivArtistHeaderCover; // 顶部伸缩区域的歌手代表封面
    private RecyclerView recyclerViewArtistSongs;
    private SongAdapter songAdapter;
    private TextView tvEmptySongsInArtist;

    private LocalMusicViewModel localMusicViewModel;
    private SharedViewModel sharedViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_artist_songs); // 需要创建此布局

        Intent intent = getIntent();
        artistId = intent.getLongExtra(EXTRA_ARTIST_ID, -1L);
        artistName = intent.getStringExtra(EXTRA_ARTIST_NAME);
        artistCoverUri = intent.getStringExtra(EXTRA_ARTIST_ALBUM_ART_URI);

        if (artistName == null) { // artistId 可以是 -1 (例如“未知艺术家”统一处理)
            Toast.makeText(this, "无效的歌手信息", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        toolbar = findViewById(R.id.toolbar_artist_songs_activity);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            // CollapsingToolbarLayout 会处理标题
        }

        collapsingToolbarLayout = findViewById(R.id.collapsingToolbarLayout_artist_songs);
        ivArtistHeaderCover = findViewById(R.id.imageView_artist_songs_header_cover);
        recyclerViewArtistSongs = findViewById(R.id.recyclerView_artist_songs_list);
        tvEmptySongsInArtist = findViewById(R.id.textView_empty_songs_in_artist);

        collapsingToolbarLayout.setTitle(artistName); // 设置折叠标题

        // 加载歌手代表封面
        if (artistCoverUri != null && !artistCoverUri.isEmpty()) {
            Glide.with(this)
                    .load(Uri.parse(artistCoverUri))
                    .placeholder(R.drawable.ic_default_artist_avatar)
                    .error(R.drawable.ic_default_artist_avatar)
                    .into(ivArtistHeaderCover);
        } else {
            ivArtistHeaderCover.setImageResource(R.drawable.ic_default_artist_avatar);
        }


        localMusicViewModel = new ViewModelProvider(this).get(LocalMusicViewModel.class);
        sharedViewModel = new ViewModelProvider(this).get(SharedViewModel.class);

        setupRecyclerView();
        observeViewModel();
    }

    private void setupRecyclerView() {
        songAdapter = new SongAdapter(
                (song, position) -> { // OnSongClickListener
                    List<Song> currentList = songAdapter.getCurrentList();
                    if (sharedViewModel != null && currentList != null && !currentList.isEmpty()) {
                        sharedViewModel.playSongAtIndex(new ArrayList<>(currentList), position);
                    }
                },
                (song, anchorView) -> { // OnSongOptionsClickListener
                    SongOptionsDialogFragment.newInstance(song.getId())
                            .show(getSupportFragmentManager(), SongOptionsDialogFragment.TAG);
                }
        );
        recyclerViewArtistSongs.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewArtistSongs.setAdapter(songAdapter);
    }

    private void observeViewModel() {
        // 从 LocalMusicViewModel 获取该歌手的歌曲列表
        // SongDao.getSongsByArtistName 需要的是歌手名
        if (artistName != null) {
            localMusicViewModel.getSongsByArtist(artistName).observe(this, songs -> {
                if (songs != null && !songs.isEmpty()) {
                    songAdapter.submitList(songs);
                    tvEmptySongsInArtist.setVisibility(View.GONE);
                    recyclerViewArtistSongs.setVisibility(View.VISIBLE);
                } else {
                    songAdapter.submitList(new ArrayList<>());
                    tvEmptySongsInArtist.setVisibility(View.VISIBLE);
                    recyclerViewArtistSongs.setVisibility(View.GONE);
                }
            });
        } else {
            tvEmptySongsInArtist.setVisibility(View.VISIBLE);
            recyclerViewArtistSongs.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
